//苹果相册heic类型 转jpeg 图片 并压缩。 非heic 压缩    苹果heic类型 会返回 {file,base64}  普通类型返回 {file}
// const convert = require('heic-convert')
class HeicToJpegAndZip {
    option = {
        maxWidth: 1000,
        maxHeight: 1000,
        maxSize: 1,
        quality: 0.92,
        mimeType: 'image/jpeg',
    }

    constructor(option) {
        this.option = Object.assign(this.option, option);
    }

    fileReader(file) {
        this.filename = file.name;
        return new Promise((resolve) => {
            let filereader = new FileReader();
            filereader.readAsArrayBuffer(file);
            filereader.onloadend = () => {
                let unit8 = new Uint8Array(filereader.result);
                if (this.isHeic(unit8)) {
                    resolve(this.covertimg(unit8));
                } else {
                    if (file.size / 1024 / 1024 > this.option.maxSize) {
                        resolve(this.zipImag(file));
                    } else {
                        resolve({
                            file: file
                        })
                    }
                }

            }
        })
    }

    async zipImag(file) {
        let image = new Image();
        let src = URL.createObjectURL(file);
        image.src = src;
        await new Promise((resolve) => {
            image.onload = function () {
                resolve();
            }
        })
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        let targetWidth = image.width / 2;
        let targetHeigh = image.height / 2;
        if (targetWidth > this.option.maxWidth || targetHeigh > this.option.maxHeight) {
            let xrate = targetWidth / this.option.maxWidth;
            let yrate = targetHeigh / this.option.maxHeight;
            let maxrate = Math.max(yrate, xrate);

            targetWidth /= maxrate;
            targetHeigh /= maxrate;
        }
        canvas.width = Math.round(targetWidth);
        canvas.height = Math.round(targetHeigh);
        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        let result = null;
        await new Promise((resolve) => {
            canvas.toBlob(function (blob) {
                resolve(blob);
            }, this.option.mimeType, this.option.quality);

        }).then((blob) => {
            URL.revokeObjectURL(src);
            result = {
                file: new File([blob], file.name, {type: this.option.mimeType})
            };
        })
        return result;

    }

    uint8ArrayUtf8ByteString(array, start, end) {
        return String.fromCharCode(...array.slice(start, end));
    }

    // brands explained: https://github.com/strukturag/libheif/issues/83
    // code adapted from: https://github.com/sindresorhus/file-type/blob/6f901bd82b849a85ca4ddba9c9a4baacece63d31/core.js#L428-L438
    isHeic(buffer) {
        const brandMajor = this.uint8ArrayUtf8ByteString(buffer, 8, 12).replace('\0', ' ').trim();
        switch (brandMajor) {
            case 'mif1':
                return true; // {ext: 'heic', mime: 'image/heif'};
            case 'msf1':
                return true; // {ext: 'heic', mime: 'image/heif-sequence'};
            case 'heic':
            case 'heix':
                return true; // {ext: 'heic', mime: 'image/heic'};
            case 'hevc':
            case 'hevx':
                return true; // {ext: 'heic', mime: 'image/heic-sequence'};
        }

        return false;
    }

    transformUint8ArrayToBase64(array) {
        var binary = "";
        for (var len = array.byteLength, i = 0; i < len; i++) {
            binary += String.fromCharCode(array[i]);
        }
        return window.btoa(binary).replace(/=/g, "");
    }


    async covertimg(inputBuffer) {
        let buffer = await convert({
            buffer: inputBuffer,
            format: this.option.mimeType.split('/')[1] === 'jpeg' ? 'JPEG' : 'PNG',
            quality: this.option.quality
        });
        return {
            // base64: "data:" + this.option.mimeType + ";base64," + this.transformUint8ArrayToBase64(buffer),
            file: new File(buffer, this.filename, {type: this.option.mimeType})
        };


    }


}

export default {
    HeicToJpegAndZip,
    //获取url后参数
    getQueryVariable: function (variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return false;
    },

    getUrlByHref(variable) {
        // 获取当前页面的 URL
        const url = new URL(window.location.href);
        // 获取 id 参数的值
        const idParam = url.searchParams.get(variable);
        // 判断 idParam 是否存在
        if (idParam) {
            // 存在 id 参数，进行相应的操作
            return idParam;
        } else {
            // id 参数不存在的处理逻辑
            return false;
        }
    },

    //日期格式转换
    dateFormat(dateStr, formatStr) {
        if (dateStr) {
            var data = null;
            try {
                data = dateStr.toString().replace(/-/g, "/");
            } catch (e) {
                data = dateStr;
            }
            return new Date(data).Format(formatStr);
        }

    }, DateAdd(interval, number, date) {//给时间加上指定数量(添加单位 需要添加数量 时间)
        switch (interval) {
            case "y": {//年
                date.setFullYear(date.getFullYear() + number);
                return date;
            }
            case "M": {//月
                date.setMonth(date.getMonth() + number);
                return date;
            }
            case "d": {//日
                date.setDate(date.getDate() + number);
                return date;
            }
            case "H": {//时
                date.setHours(date.getHours() + number);
                return date;
            }
            case "m": {//分
                date.setMinutes(date.getMinutes() + number);
                return date;
            }
            case "s": {//秒
                date.setSeconds(date.getSeconds() + number);
                return date;
            }
            default: {//默认按天计算
                date.setDate(date.getDate() + number);
                return date;
            }
        }
    }, getUrlParam(name) {//hash获取url参数
        const after = window.location.hash.split("?", 2)[1];
        if (after) {
            const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            const r = after.match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            } else {
                return false;
            }
        }
    }, setCookie(c_name, value) {//写cookies
        document.cookie = c_name + "=" + escape(value);
    }, getCookie(name) {//读取cookies
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
        else return null;
    }, delCookie(name) {//删除cookies
        var exp = new Date();
        exp.setTime(exp.getTime() - 100);
        var cval = this.getCookie(name);
        if (cval != null)
            document.cookie = name + "=" + cval + ";expires=" + exp.toUTCString();
    }, calculateDiscount(lat1, lng1, lat2, lng2) {//计算两个经纬度之间的距离
        const radLat1 = (lat1 * Math.PI) / 180.0;
        const radLat2 = (lat2 * Math.PI) / 180.0;
        const a = radLat1 - radLat2;
        const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
        let s =
            2 *
            Math.asin(
                Math.sqrt(
                    Math.pow(Math.sin(a / 2), 2) +
                    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
                )
            );
        s = s * 6378.137; // EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        s = s * 1000;
        if (isNaN(s)) {
            return 0;
        }
        // 小于1000米直接返回
        return s.toFixed();
    }
}
//将日期转换成指定格式的字符串
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
            "00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
